﻿using AntdUI;
using System;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using System.Windows.Forms;
using WenAntdUI.Helps;
using WenAntdUI.Interfaces;
using Button = AntdUI.Button;

namespace WenAntdUI.Dome
{
    public partial class Form4 : UserControl
    {
        public Form4()
        {
            InitializeComponent();


            this.menu1.SelectChanged += Menu1_SelectChanged;


            this.modelEditControl1.GetItemBuilder(value)
                .Add(a => a.Color)
                .Add(a => a.Name)
                .Add(a => a.CreateTime)
                .Add(a => a.Image)
                //.Add(a => a.Aa)
                //.Add(a => a.Name, content: new DictSelect("1"))
                .Add(a => a.KK)
                .Add(a => a.Dict)
                .Add(a => a.KKd)
                .Add(a => a.Typ)
                .Add(a => a.TestEditControlTest, content: new TestEditControl())
                .Add(a => a.Check);

            this.adminTable1.SetColumns<A>();

            this.adminTable1.CellClick += AdminTable1_CellClick;


            //this.input1.DataBinding(value, a => a.Text, b => b.Name);

            //var notifyWrapper = new Notify<A>(value);

            //this.input1.DataBinding(notifyWrapper, "Text", "[\"Name\"]");

            //Dictionary<string, string> keys = new Dictionary<string, string>
            //{
            //    { "Name", "名称测试" }
            //};
            bl = new BindingList<A>
            {
                value
            };
            var bindingSource = new BindingSource(bl, null);
            //bindingSource.DataSource = new BindingList<KeyValuePair<string, string>>(keys.ToList());
            var bind = new Binding("Text", bindingSource, "Name", false, DataSourceUpdateMode.OnPropertyChanged);

            this.input1.DataBindings.Add(bind);

            

            //var notifyWrapper = new Notify<A>(value);

            
        }

        private BindingList<A> bl;


        private void AdminTable1_CellClick(object sender, TableClickEventArgs e)
        {
            var obj = e.Record as A;
            if (e.RowIndex < 1)
                return;
            this.modelEditControl1.Model = (this.adminTable1.DataSource as IList)[e.RowIndex - 1] as A;
            bl[0] = obj;
        }

        private void Menu1_SelectChanged(object sender, MenuSelectEventArgs e)
        {
            var menuitems = this.menu1.Items.ToList<MenuItem>();
            var menuSelectItem = this.menu1.GetSelectItem();
            var ddd = e.Value;
        }

        public A value { get; set; } = new A();


        public partial class A //: ObservableObject
        {
            [Key]
            public Guid Id { get; set; }
            //[ObservableProperty]
            public int aa = 56;

            [DisplayName("测试选择框")]
            public bool Check { get; set; } = true;

            [DisplayName("测试数字1")]
            [Col]
            public int KK { get; set; }
            [DisplayName("测试数字")]
            [Col]
            public decimal KKd { get; set; } = 15.5m;

            [DisplayName("名称测试")]
            [Col]
            public string Name { get; set; } = "1";

            [DisplayName("字典测试")]
            [Dict("0")]
            [Col]
            public string Dict { get; set; } = "00代码";

            [DisplayName("测试自定义控件")]
            [Col]
            public string TestEditControlTest { get; set; } = "999999";
            [DisplayName("测试颜色")]
            [Col]
            public Color Color { get; set; } = Color.Red;
            [DisplayName("测试枚举")]
            [Col]
            public Atyp Typ { get; set; } = Atyp.A;

            [DisplayName("测试时间")]
            [Col]
            public DateTime CreateTime { get; set; }//= DateTime.Now;

            [DisplayName("测试TimeSpan")]
            public TimeSpan TimeSpan { get; set; } = new TimeSpan(1000);

            [DisplayName("图片测试")]
            [Col]
            public Image Image { get; set; } //= Image.FromFile("1.png");
        }

        public enum Atyp
        {
            Node,
            [Description("测试名称A")]
            A,
            [Description("测试名称B")]
            B,
            C,
            D,
        }


        public class TestEditControl : Control, IEditControl
        {

            public TestEditControl()
            {
                input = new Input() { Dock = DockStyle.Fill };
                this.Controls.Add(input);

                input.TextChanged += (s, e) => ValueChanged?.Invoke(this, input.Text);
                this.Height = 50;



                var button = new Button() { Dock = DockStyle.Right, Text = "自定义控件按钮", Width = 130 };
                this.Controls.Add(button);

                //this.input.DataBinding(this, "Text", "Value");
            }

            private readonly Input input;
            public object Value { get => input.Text; set => input.Text = value.ToString(); }
            public event EventHandler<object> ValueChanged;

            public void SetValue(object value)
            {
                input.Text = (string)value;
                this.Value = value;
            }
        }

        private async void Button1_Click(object sender, EventArgs e)
        {
            ////a.TestEditControlTest = "333332";
            ////a.Name = "8888";
            ////a.Color = Color.Green;
            ////a.Dict = "11";
            ////a.Aa = 999;

            //var channel = GrpcChannel.ForAddress("http://localhost:5985");


            //var client2 = new Auther.AutherClient(channel);
            //var r = client2.Auth(new AuthRequest() { Username = "admin", Password = "admin" });


            //var headers = new Metadata()
            //{
            //    {"Authorization", $"Bearer {r.Token}" }
            //};

            ////var client = new Greeter.GreeterClient(channel);
            ////var reply = client.SayHello(new HelloRequest { Name = "GreeterClient" }, headers);
            ////MessageBox.Show(reply.Message);


            //var client = new FileClient("http://localhost:5985", headers);
            //await client.UploadFileAsync("E:\\影视\\电影\\末日 The End (2024).mp4");

            ////var client = new Fileer.FileerClient(channel);

            ////using var call = client.UploadFile(headers);

            ////using var fileStream = File.OpenRead("1.png");

            ////client.UploadFile("1.png", headers);


            ////byte[] buffer = new byte[1024 * 1024];
            ////int bytesRead;
            ////while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            ////{
            ////    call.RequestStream.WriteAsync(new FileChunk
            ////    {
            ////        FileName = "1.png",
            ////        Content = ByteString.CopyFrom(buffer, 0, bytesRead)
            ////    }).GetAwaiter().GetResult();
            ////}
            ////call.RequestStream.CompleteAsync().GetAwaiter();
            ////var status = call.ResponseAsync.GetAwaiter().GetResult();
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            value.TestEditControlTest = "333332";
            value.Name = "888899999999999999999";
            value.Color = Color.Green;
            value.Dict = "11";
        }

        private async void UploadFile1_UploadClick(object sender, string e)
        {
            var token = await new AuthClient().GetTokenAsync("admin", "admin");

            var fu = new FileUploader(token);

            IProgress<double> progress = new Progress<double>(a =>
            {
                this.uploadFile1.ProgressValue = (float)a / 100;
            });

            await fu.UploadFileAsync(e, progress);
        }

        private async void Button3_Click(object sender, EventArgs e)
        {
            IProgress<double> progress = new Progress<double>(a =>
            {
                this.uploadFile1.ProgressValue = (float)a / 100;
            });
            var token = await new AuthClient().GetTokenAsync("admin", "admin");
            var fd = new FileDownloader(token);
            await fd.DownloadFileAsync(Guid.Parse("67fe9287-f4d5-b5d8-00ef-0c035f10cb40"), "D:\\123.mp4", progress);
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            this.adminTable1.Table.Invalidate();
            this.adminTable1.Table.Refresh();
        }

        private async void Button5_Click(object sender, EventArgs e)
        {
            await RefreshDataAsync();
        }

        private async Task RefreshDataAsync()
        {
            var client = new ApiClient();
            var res = await client.GetListAsync(typeof(SysDict), "", true, 1, 5);
            this.table1.DataSource = res.Data;
        }

        private async void Button6_Click(object sender, EventArgs e)
        {
            var item = GetSelectItem();
            if (item is null) return;

            item.Name = DateTime.Now.ToString();

            var client = new ApiClient();
            var res = client.UpdateObject(item);
            await RefreshDataAsync();
        }

        private async void Button7_Click(object sender, EventArgs e)
        {
            var item = GetSelectItem();
            if (item is null) return;

            item.Name = DateTime.Now.ToString();

            var client = new ApiClient();
            var res = client.DeleteObject(item);
            await RefreshDataAsync();
        }

        private async void Button8_Click(object sender, EventArgs e)
        {
            var item = GetSelectItem();
            if (item is null) return;

            item.Name = DateTime.Now.ToString();
            item.Id = 0;

            var client = new ApiClient();
            var res = client.InsertObject(item);
            await RefreshDataAsync();
        }

        private SysDict GetSelectItem()
        {
            if (this.table1.SelectedIndex > 0)
                return (this.table1.DataSource as IList)[this.table1.SelectedIndex - 1] as SysDict;
            else
                return null;
        }
    }
}
